package persistence.impl;

import domain.Product;
import persistence.DBUtil;
import persistence.ProductDAO;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class ProductDAOImpl implements ProductDAO {
    private static final String GET_PRODUCT_BY_ID =
            "SELECT * FROM product WHERE product_id=?";
    private static final String GET_PRODUCT_BY_SPECIES_OR_BREED =
            "SELECT * FROM product WHERE species LIKE ? OR breed LIKE ?";

    @Override
    public Product getProductById(String productid) {
        Product product = null;
        try {
            Connection connection = DBUtil.getConnection();
            PreparedStatement preparedStatement = connection.prepareStatement(GET_PRODUCT_BY_ID);
            preparedStatement.setString(1, productid);
            ResultSet resultSet = preparedStatement.executeQuery();
            if (resultSet.next()){
                product = toProduct(resultSet);
            }
            DBUtil.closeResultSet(resultSet);
            DBUtil.closeStatement(preparedStatement);
            DBUtil.closeConnection(connection);
        }catch (Exception e){
            e.printStackTrace();
        }
        return product;
    }

    @Override
    public List<Product> getProductBySpeciesOrBreed(String species, String breed) {
        List<Product> productList = new ArrayList<>();
        try {
            Connection connection = DBUtil.getConnection();
            PreparedStatement preparedStatement = connection.prepareStatement(GET_PRODUCT_BY_SPECIES_OR_BREED);
            preparedStatement.setString(1, "%" + species + "%");
            preparedStatement.setString(2, "%" + breed + "%");
            ResultSet resultSet = preparedStatement.executeQuery();
            while (resultSet.next()){
                productList.add(toProduct(resultSet));
            }
            DBUtil.closeResultSet(resultSet);
            DBUtil.closeStatement(preparedStatement);
            DBUtil.closeConnection(connection);
        }catch (Exception e){
            e.printStackTrace();
        }
        return productList;
    }

    private Product toProduct(ResultSet resultSet){
        Product product = new Product();
        try {
            product.setProductId(resultSet.getString("product_id"));
            product.setSpecies(resultSet.getString("species"));
            product.setDescr(resultSet.getString("descr"));
            product.setBreed(resultSet.getString("breed"));
            product.setUnitprice(resultSet.getBigDecimal("unit_price"));
            product.setImageSrc(resultSet.getString("img_src"));
        }catch (Exception e){
            e.printStackTrace();
        }
        return product;
    }
}
